      1  import java.util.Scanner;

      2  import java.util.Stack;

      3

      4  /**

      5     This calculator uses the reverse Polish notation.

      6  */

      7  public class Calculator

      8  {

      9     public static void main(String[] args)

     10     {

     11        Scanner in = new Scanner(System.in);

     12        Stack<Integer> results = new Stack<Integer>();

     13        System.out.println("Enter one number or operator per line, Q to quit. ");

     14        boolean done = false;

     15        while (!done)

     16        {

     17           String input = in.nextLine();

     18

     19           // If the command is an operator, pop the arguments and push the result

     20

     21           if (input.equals("+"))

     22           {

     23              results.push(results.pop() + results.pop());

     24           }

     25           else if (input.equals("-"))

     26           {

     27              Integer arg2 = results.pop();

     28              results.push(results.pop() - arg2);

     29           }

     30           else if (input.equals("*") || input.equals("x"))

     31           {

     32              results.push(results.pop() * results.pop());

     33           }

     34           else if (input.equals("/"))

     35           {

     36              Integer arg2 = results.pop();

     37              results.push(results.pop() / arg2);

     38           }

     39           else if (input.equals("Q") || input.equals("q"))

     40           {

     41              done = true;

     42           }

     43           else

     44           {

     45              // Not an operator--push the input value

     46

     47              results.push(Integer.parseInt(input));

     48           }

     49           System.out.println(results);

     50        }

     51     }

     52  }